import os
import sys

from mon.baselib.utils import FileUtils, StringUtils

from src.utils import PyautoguiUtils


def default_config() -> list:
    """默认配置"""
    df_config = [
        "#左上角坐标",
        "zuo_shang_jiao=0,0",
        "#抢红包坐标",
        "new_origin=0,0",
        "#调整x坐标",
        "adjust_x=0",
        "#调整y坐标",
        "adjust_y=0",
        "#每次抢完随机暂停时间",
        "random_sleep=1,10",
        "#是否抢完锁定电脑",
        "finish_lock=False",
        "#是否抢完关闭电脑",
        "finish_close=False"
    ]
    return df_config


def get_config_dir() -> str:
    exe_dir = os.path.dirname(sys.executable)
    return os.path.join(exe_dir, 'config')


def get_config_dir_file(file_name: str) -> str:
    exe_dir = os.path.dirname(sys.executable)
    return os.path.join(exe_dir, 'config', file_name)


def get_config_file() -> str:
    config_dir = get_config_dir()
    return os.path.join(config_dir, 'config.txt')


def create_default_config_file() -> None:
    """如果配置不存在，则将默认配置写入默认配置文件"""
    config_dir = get_config_dir()
    if not os.path.exists(config_dir):
        os.makedirs(config_dir)
    config_file = get_config_file()
    if not os.path.exists(config_file):
        with open(config_file, 'w') as f:
            f.write('\n'.join(default_config()))


def get_config_params() -> dict:
    """获取配置参数"""
    config_file = get_config_file()
    return FileUtils.read_config_file_to_dict(config_file)


def get_image_full_path(image_name: str) -> str:
    """获取图片的完整路径"""
    return os.path.join(get_config_dir(), image_name)


def config_to_tuple(s: str, df=(1, 10)) -> tuple:
    if StringUtils.is_empty(s):
        return df
    items = s.split(',')
    if len(items) == 1:
        return df
    if StringUtils.is_empty(items[0]) or StringUtils.is_empty(items[1]):
        return df
    return tuple(int(item.strip()) for item in items)


def get_config_value(key: str, df=None) -> str:
    config_dict = get_config_params()
    return config_dict.get(key, df)


def get_new_origin() -> tuple:
    config_dict = get_config_params()
    new_origin = config_dict.get("new_origin")
    return config_to_tuple(new_origin)


def screenshot(config_dict: dict, screenshot_mark: str) -> str:
    zuo_shang_jiao = config_to_tuple(config_dict['zuo_shang_jiao'])
    width = 554
    height = 986
    app_screenshot_path = os.path.join(get_config_dir(), screenshot_mark + '_app_screenshot_path.png')
    PyautoguiUtils.capture_region_width_height(zuo_shang_jiao[0], zuo_shang_jiao[1], width, height, app_screenshot_path)
    return app_screenshot_path


def str_to_bool(s: str):
    return StringUtils.str_to_bool(s)
